package com.lihao.wanandroid.app.weight.recyclerview

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * Created by lihao on 2020/6/17.
 * Describe: 解决和嵌套ViewPager2滑动冲突的问题
 */
class ScrollClashRecyclerView : RecyclerView {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet?, style: Int) : super(context, attrs, style)

    private var startX: Int = 0
    private var startY: Int = 0

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                startX = ev.x.toInt()
                startY = ev.y.toInt()
                parent.requestDisallowInterceptTouchEvent(true)
            }
            MotionEvent.ACTION_MOVE -> {
                val endX = ev.x.toInt()
                val endY = ev.y.toInt()
                val disX: Int = Math.abs(endX - startX)
                val disY: Int = Math.abs(endY - startY)
                val lm = layoutManager as LinearLayoutManager
                if (lm.orientation == VERTICAL) {
                    if (disX < disY) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else if (2 * disY < disX) {
                        parent.requestDisallowInterceptTouchEvent(false)
                    }
                } else {
                    if (disX > disY) {
                        parent.requestDisallowInterceptTouchEvent(true)
                    } else if (2 * disX < disY) {
                        parent.requestDisallowInterceptTouchEvent(false)
                    }
                }

            }
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> parent.requestDisallowInterceptTouchEvent(
                false
            )
        }
        return super.dispatchTouchEvent(ev)
    }
}